package com.matchmealpha;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class PostActivity extends Activity implements OnClickListener {

	private LinearLayout buttonLayout;
	private Button leftButton;
	private Button rightButton;
	private TextView headerText;

	private TextView date1;
	private TextView user1;
	private TextView location1;
	private TextView text1;

	private TextView date2;
	private TextView user2;
	private TextView location2;
	private TextView text2;

	private ImageView pic;

	private TextView tagText;

	private TextView likeText;

	private ListView commentLayout;
	private ArrayList<Comment> commentList;
	private CommentListAdapter commentAdapter;
	
	private ArrayList<String> likeList;

	private Button moreButton;
	private Button likeButton;
	private Button commentButton;

	private Bundle bund;
	private int callerID; // 1 - recent, 2 - alert, 3 - timeline, 4 - friends
	private Post post;
	private int position;
	private Context context;

	private String username;
	private String sessionid;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.context = this.getParent();

		/*** Shared Pref ***/
		SharedPreferences settings = getSharedPreferences(
				"matchme_preferences", 0);
		username = settings.getString("username", "");
		sessionid = settings.getString("sessionid", "");

		/*** Saving Bundles Data ***/
		bund = this.getIntent().getExtras();
		if (bund != null) {
			callerID = bund.getInt("callerID");
			position = bund.getInt("postIndex");
			Log.d("POST ACTIVITY", "POST ID is:" + position);
			switch (callerID) {
			case MatchMeTabWidget.TIMELINE:
				post = MatchMeTabWidget.timelineList.get(position);
				break;
			case MatchMeTabWidget.RECENT:
				post = MatchMeTabWidget.recentList.get(position);
				break;
			}
		} else
			Log.d("ERROR", "SHOULD NOT BE HERE");

		initLayout();
		initListener();
		

		/*** Comment List ***/
		commentList = new ArrayList<Comment>();
		commentAdapter = new CommentListAdapter(this.getParent(), commentList,
				callerID);
		commentLayout.setAdapter(commentAdapter);
		
		/*** Like List ***/
		likeList = new ArrayList<String>();
		
		//commentLayout.addFooterView(buttonLayout);
		
		// TODO get comment list from the server
		setPostItem();

	}

	private void initListener() {
		leftButton.setOnClickListener(this);
		user1.setOnClickListener(this);
		user2.setOnClickListener(this);
		location1.setOnClickListener(this);
		location2.setOnClickListener(this);
		moreButton.setOnClickListener(this);
		likeButton.setOnClickListener(this);
		commentButton.setOnClickListener(this);
	}

	private void initLayout() {
		setContentView(R.layout.post_view);
		buttonLayout = (LinearLayout) this.findViewById(R.id.PostButtonLayout);
		leftButton = (Button) this.findViewById(R.id.PostLeftButton);
		rightButton = (Button) this.findViewById(R.id.PostRightButton);
		headerText = (TextView) this.findViewById(R.id.PostHeaderText);

		date1 = (TextView) this.findViewById(R.id.PostDate1Text);
		user1 = (TextView) this.findViewById(R.id.PostUser1Text);
		location1 = (TextView) this.findViewById(R.id.PostLocation1Text);
		text1 = (TextView) this.findViewById(R.id.PostText1Text);

		date2 = (TextView) this.findViewById(R.id.PostDate2Text);
		user2 = (TextView) this.findViewById(R.id.PostUser2Text);
		location2 = (TextView) this.findViewById(R.id.PostLocation2Text);
		text2 = (TextView) this.findViewById(R.id.PostText2Text);

		pic = (ImageView) this.findViewById(R.id.PostPicImage);
		likeText = (TextView) this.findViewById(R.id.PostLikeText);
		tagText = (TextView) this.findViewById(R.id.PostTagText);
		commentLayout = (ListView) this.findViewById(R.id.PostCommentList);

		moreButton = (Button) this.findViewById(R.id.PostMoreButton);
		likeButton = (Button) this.findViewById(R.id.PostLikeButton);
		commentButton = (Button) this.findViewById(R.id.PostCommentButton);

		rightButton.setVisibility(View.INVISIBLE);
	}

	private void setPostItem() {
		headerText.setText(post.getUserID1() + " & " + post.getUserID2());

		date1.setText(post.getTime1());
		user1.setText(post.getUserID1());
		location1.setText(post.getLocation1());
		text1.setText(post.getDescription1());

		// TODO display date2 - need to save date2
		user2.setText(post.getUserID2());
		location2.setText(post.getLocation2());
		text2.setText(post.getDescription2());
		pic.setImageBitmap(post.getBitMapImage());
		
		//Likes
		String likes = "Likes: ";
		HttpRequest req2 = new HttpRequest(sessionid);
		String response2;
		response2 = req2.sendPost(MatchMeTabWidget.MM_SERVER
				+ "/get_likes/" + post.getPostID(), "");
		if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response2))
			Log.d("POST ACT --------", "Error downloading likes:" + response2);
		else if (response2 != null) {
			Scanner in = new Scanner(response2).useDelimiter(";");
			while (in.hasNext()) {
				likeList.add(in.hasNext() + ", ");
			}
		}
		post.setLikeList(likeList);
		
		//Comments
		HttpRequest req = new HttpRequest(sessionid);
		String response;
		response = req.sendPost(MatchMeTabWidget.MM_SERVER
				+ "/get_comments/" + post.getPostID(), "");
		if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response))
			Log.d("POST ACT --------", "Error downloading comments:" + response);
		else if (response != null) {
			Scanner in = new Scanner(response).useDelimiter(";");
			Comment c;
			while (in.hasNext()) {
				c = new Comment();
				c.setPostID(post.getPostID());
				c.setUserID(in.next());
				c.setDescription(in.next());
				c.setTimestamp(in.next());
				commentList.add(c);
			}
		}
		post.setCommentList(commentList);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case (R.id.PostLeftButton):
			MatchMeTabWidget.myBack(this.callerID);
			break;
		case (R.id.PostUser1Text):
			Intent intent = new Intent(this, TimelineActivity.class);
			intent.putExtra("back", true);
			intent.putExtra("callerID", this.callerID);
			View view = MatchMeTabWidget.getCurrGroup(this.callerID)
					.getLocalActivityManager().startActivity(
							"TimelineActivity",
							intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
					.getDecorView();
			MatchMeTabWidget.myReplaceView(view, this.callerID);
			break;
		case (R.id.PostUser2Text):
			Intent intent2 = new Intent(this, TimelineActivity.class);
			intent2.putExtra("back", true);
			intent2.putExtra("callerID", this.callerID);
			View view2 = MatchMeTabWidget.getCurrGroup(this.callerID)
					.getLocalActivityManager().startActivity(
							"TimelineActivity",
							intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
					.getDecorView();
			MatchMeTabWidget.myReplaceView(view2, this.callerID);
			break;
		case (R.id.PostMoreButton):
			MatchMeTabWidget.mFacebook.authorize(this.getParent(),
					MatchMeTabWidget.FB_PERMISSIONS,
					new WallPostDialogListener(this.getParent(), post.getPostID()));
			/*
			 * byte[] barray = MatchMeTabWidget.intArrayToByte(post.getPicID());
			 * Bundle params = new Bundle(); params.putString("method",
			 * "photos.upload"); params.putByteArray("picture", barray);
			 * 
			 * MatchMeTabWidget.mAsyncRunner.request(null, params, "POST", new
			 * WallPostDialogListener(this.getParent()), null);
			 */break;
		case (R.id.PostLikeButton):
			HttpRequest req = new HttpRequest(sessionid);
			String response;
			response = req.sendPost(MatchMeTabWidget.MM_SERVER
					+ "/add_like/" + post.getPostID() + "/" + username, "");
			if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response))
				Log.d("PostACTIVITY ---- ", "Uploading like failed");
			else if (response != null) {
				if (response != "") {
					post.getLikeList().add(username);
					likeText.postInvalidate();
					// TODO update the server every X secs - don't need toupdate commentList here
				}
			}
			break;
		case (R.id.PostCommentButton):
			final AlertDialog.Builder alert = new AlertDialog.Builder(
					getParent());
			final EditText input = new EditText(this);
			alert.setView(input);
			alert.setMessage("Enter Comment");
			alert.setPositiveButton("Ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							String value = input.getText().toString();
							
							if (!value.equals("")) {
								// TODO save to server
								HttpRequest req = new HttpRequest(sessionid);
								String response;
								response = req.sendPost(MatchMeTabWidget.MM_SERVER + "/add_comment/"
										+ post.getPostID() + "/" + username + "/" + value, "");
								if (MatchMeTabWidget.USER_AUTH_FAILURE.equals(response)
										|| MatchMeTabWidget.REQUEST_FAILURE.equals(response))
									Log.d("PostACTIVITY ---- " , "Uploading comment failed");
								else if (response != null) {
									if (response != "") {
										Comment c = new Comment();
										c.setUserID(username);
										c.setDescription(value);
										c.setPostID(post.getPostID());
										//commentList.add(new CommentView(context,c,callerID));
										//commentLayout.invalidate();
										post.getCommentList().add(c);
										commentAdapter.notifyDataSetChanged();
										// TODO update the server every X secs - don't need toupdate commentList here
									}
								}
							}
						}
					});

			alert.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
						}
					});
			alert.show();
			break;
		}

	}

}
